#!/usr/bin/env ruby
 
require File.dirname(__FILE__) + '/../config/boot'
 
require 'webrick'
require 'webrick/https'
 
puts "=> Booting WEBrick..."
 
OPTIONS = {
  :port         => 3001,
  :ip           => "127.0.0.1",
  :environment  => (ENV['RAILS_ENV'] || "production").dup,
  :server_root  => File.expand_path(RAILS_ROOT + "/public/"),
  :pkey         => OpenSSL::PKey::RSA.new(
                      File.open(RAILS_ROOT + "/config/certs/server.key").read),
  :cert         => OpenSSL::X509::Certificate.new(
                      File.open(RAILS_ROOT + "/config/certs/server.crt").read),
  :server_type  => WEBrick::SimpleServer,
  :charset      => "UTF-8",
  :mime_types   => WEBrick::HTTPUtils::DefaultMimeTypes,
  :debugger     => false
}
 
ENV["RAILS_ENV"] = OPTIONS[:environment]
RAILS_ENV.replace(OPTIONS[:environment]) if defined?(RAILS_ENV)
 
require RAILS_ROOT + "/config/environment"
require 'webrick_server'
OPTIONS['working_directory'] = File.expand_path(RAILS_ROOT)
 
class SSLDispatchServlet < DispatchServlet
  def self.dispatch(options)
    Socket.do_not_reverse_lookup = true
    server = WEBrick::HTTPServer.new(
      :Port             => options[:port].to_i,
      :ServerType       => options[:server_type],
      :BindAddress      => options[:ip],
      :SSLEnable        => true,
      :SSLVerifyClient  => OpenSSL::SSL::VERIFY_NONE,
      :SSLCertificate   => options[:cert],
      :SSLPrivateKey    => options[:pkey],
      :SSLCertName      => [ [ "CN", WEBrick::Utils::getservername ] ]
    )
 
    server.mount('/', DispatchServlet, options)
    trap("INT") { server.shutdown }
 
    server.start
  end
end
 
puts "=> Rails application started on https://#{OPTIONS[:ip]}:#{OPTIONS[:port]}"
puts "=> Ctrl-C to shutdown"
 
 
SSLDispatchServlet.dispatch(OPTIONS)